#! _*_ coding:utf8 _*_
# coding=utf-8
import re
import time
import random

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import json

'''
发送短信的模块
'''

MSG_APP_KEY = '2e5b7cf465a2482255b6c9b0987a824b'
MSG_ACCESS_KEYID = 'LTAIqf5WiT0vbq26'
MSG_ACCESS_SECRECT = 'NnWDj4ro0Dmvx05VZfNXdXHJiP569e'
MSG_SIGN_NAME = "待课"
MSG_TEMPLATE_CODE = 'SMS_167528486'


def generate_verify_code():
    return str(random.random())[-4:]


def check_phone_number(phone):
    p2 = re.compile('^0\d{2,3}\d{7,8}$|^1[358]\d{9}$|^147\d{8}')
    phonematch = p2.match(phone)
    return phonematch


def real_verify_code(vcode):
    expire = 60 * 5  # 5 minutes
    current_time_sec = int(time.time())
    time_prefix = current_time_sec / expire
    real_code = str(time_prefix) + '-' + vcode
    return real_code


def send_verify_code_to(code, phone):
    if not code or not phone:
        return False

    client = AcsClient(MSG_ACCESS_KEYID, MSG_ACCESS_SECRECT, 'default')

    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('PhoneNumbers', phone)
    request.add_query_param('SignName', MSG_SIGN_NAME)
    request.add_query_param('TemplateCode', MSG_TEMPLATE_CODE)
    request.add_query_param('TemplateParam', {"code": code})

    response = client.do_action(request)

    res = json.loads(response)
    if res.get("Code", None) != "OK":
        return False

    return True


if __name__ == '__main__':
    send_verify_code_to('1288', '13297931810')
